
import serial
import time
import glob
import threading


class EnvTest:

    def __init__(self, command) -> None:

        self.command = command

    def get_tty_path(self) -> list:

        return glob.glob("/dev/ttyUSB*")
    
    @staticmethod
    
    def work(ttyUSB, command):

        try:

            ser = serial.Serial(ttyUSB, 115200)

            time.sleep(2)

            ser.write(command.encode())

            time.sleep(2)

            response = ser.read_all()

            print(response)

            print(response.decode())
        
        finally:

            ser.close()

    def start_threads(self):
        tty_paths = self.get_tty_path()
        threads = []
        
        # 根据 tty_paths 列表的个数开启对应数量的线程
        for i, tty_path in enumerate(tty_paths):
            thread = threading.Thread(target=self.work, args=(tty_path, self.command))
            thread.start()
            threads.append(thread)

        # 等待所有线程执行完毕
        for thread in threads:
            thread.join()

    








# # 打开串口，默认波特率为9600
# ser = serial.Serial('/dev/ttyUSB0', 115200)

# # 等待一段时间，以确保串口已经初始化
# time.sleep(2)

# # 发送命令
# command = "AT+JOIN\r\n"
# ser.write(command.encode())

# # 等待一段时间，以确保命令已经发送完毕
# time.sleep(2)

# # 读取返回数据
# response = ser.read_all()
# print(response)

# # 关闭串口
# ser.close()

if __name__ == "__main__":

    e = EnvTest("at+join")

    x = e.start_threads()

